﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace AjaxUploadServer
{
	public interface IJsonData<T> : IDictionary<string, T>
	{
		void CopyFrom(IJsonData<T> target, bool clear);
		bool TryParse<TT>(string name, out TT output);
	}

	public class JsonData<T> : IJsonData<T>
	{
		public JsonData()
		{
			data = new Dictionary<string, T>();
		}
		protected readonly IDictionary<string, T> data;

		public ICollection<string> Keys
		{
			get { return data.Keys; }
		}
		public int Count
		{
			get { return data.Count; }
		}

		public T this[string key]
		{
			get { return data[key]; }
			set { data[key] = value; }
		}

		public bool ContainsKey(string key)
		{
			return data.ContainsKey(key);
		}

		public void Add(string key, T value)
		{
			data.Add(key, value);
		}

		public bool Remove(string key)
		{
			return data.Remove(key);
		}

		public bool TryGetValue(string key, out T value)
		{
			return data.TryGetValue(key, out value);
		}

		public void Clear()
		{
			data.Clear();
		}

		public bool TryParse<TT>(string key, out TT output)
		{
			if (!this.ContainsKey(key))
			{
				output = default(TT);
				return false;
			}
			object obj;
			bool b = false;
			var conv = new Converter<T, TT>(delegate (T t)
			{
				try
				{
					obj = Convert.ChangeType(this[key], Type.GetTypeCode(typeof(TT)));
					b = true;
				}
				catch
				{
					obj = default(TT);
					b = false;
				}
				return (TT)obj;
			});
			output = conv.Invoke(this[key]);
			return b;
		}

		public virtual void CopyFrom(IJsonData<T> target, bool clear)
		{
			if (clear) this.Clear();
			foreach (string key in target.Keys)
			{
				this[key] = target[key];
			}
		}
		public ICollection<T> Values
		{
			get { return data.Values; }
		}

		#region 显示实现接口


		bool ICollection<KeyValuePair<string, T>>.IsReadOnly
		{
			get { return true; }
		}

		void ICollection<KeyValuePair<string, T>>.Add(KeyValuePair<string, T> item)
		{
			throw new NotImplementedException();
		}

		bool ICollection<KeyValuePair<string, T>>.Contains(KeyValuePair<string, T> item)
		{
			throw new NotImplementedException();
		}

		void ICollection<KeyValuePair<string, T>>.CopyTo(KeyValuePair<string, T>[] array, int arrayIndex)
		{
			throw new NotImplementedException();
		}

		bool ICollection<KeyValuePair<string, T>>.Remove(KeyValuePair<string, T> item)
		{
			throw new NotImplementedException();
		}

		IEnumerator<KeyValuePair<string, T>> IEnumerable<KeyValuePair<string, T>>.GetEnumerator()
		{
			return data.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return data.GetEnumerator();
		}

		#endregion
	}
}